package com.carkeeper.controller;

import com.carkeeper.dto.DepartmentDTO;
import com.carkeeper.pojo.DepartmentPO;
import com.carkeeper.service.DepartmentService;
import com.carkeeper.vo.DepartmentVO;
import com.carkeeper.vo.Pager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;

    @GetMapping
    public Pager<DepartmentPO> queryPage(@RequestParam(name = "code", required = false) String code,
                                         @RequestParam(name = "name", required = false) String name,
                                         @RequestParam(name = "page", defaultValue = "1") Long page,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Long pageSize) {
        return new Pager(departmentService.query(code, name, page, pageSize));
    }

    @PostMapping
    public Boolean create(@RequestBody DepartmentVO vo) {
        if (departmentService.has(vo.getCode())) return false;

        DepartmentPO po = new DepartmentPO();
        po.setCode(vo.getCode());
        po.setName(vo.getName());

        po.setCreateTime(LocalDateTime.now());

        departmentService.create(po);

        return true;
    }

    @GetMapping("/{id}")
    public DepartmentVO findById(@PathVariable Long id) {
        DepartmentVO vo = new DepartmentVO();
        DepartmentPO po = departmentService.getById(id);
        if (po == null) {
            return null;
        }
        BeanUtils.copyProperties(po, vo);

        return vo;
    }

    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Long id) {
        return departmentService.delete(id);
    }

    @PutMapping("/{id}")
    public Boolean update(@PathVariable Long id, @RequestBody DepartmentVO vo) {
        DepartmentPO po = new DepartmentPO();
        po.setName(vo.getName());
        po.setCode(vo.getCode());
        po.setId(id);

        return departmentService.update(po);
    }

    @PostMapping("/list")
    public List<DepartmentDTO> getByIds(@RequestBody List<Long> ids) {
        if (ids == null) return new ArrayList<DepartmentDTO>();
        return departmentService.findAll(ids);
    }
}
